<?php 
global $_GPC, $_W;
$cfg = $this->module['config'];
session_start();
$userid=$_GPC['_userid'];
if(!$userid){
	header("location:".$this->createMobileUrl('login'));
	exit();
}
$operation = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
$user=pdo_fetch("SELECT * FROM " . tablename('j_hmoney_user') . " WHERE id =:a",array(":a"=>$userid));
if(!$user || !$user['status'])message('请添加门店和员工信息！', '', 'error');
$shop=pdo_fetch("SELECT * FROM " . tablename('j_hmoney_group') . " WHERE id =:a",array(":a"=>$user['pcate']));
$shopid=$shop['id'];
load()->model('mc');

if ($operation == 'display') {
	$categoryary=array();
	foreach($tablepcatelist as $row){
		$categoryary[$row['id']]=$row['title'];
	}
	$goodpcatelist = pdo_fetchall("SELECT * FROM " . tablename('j_hmoney_goodcategory') . " WHERE weid = '".$_W['uniacid']."' and groupid ='".$shopid."' and status=1 order by  displayorder asc, id desc");
	
	$isNoPcate=pdo_fetchcolumn("SELECT count(*) FROM ".tablename('j_hmoney_goods')." WHERE weid = '".$_W['uniacid']."' and groupid ='".$shopid."' and pcate=0");
	$isfungood=pdo_fetchcolumn("SELECT count(*) FROM ".tablename('j_hmoney_goodmarket')." WHERE weid = '".$_W['uniacid']."' and groupid ='".$shopid."' and status=1 and starttime<='".TIMESTAMP."' and endtime>='".TIMESTAMP."' and contentid<>'' ");
} elseif ($operation == 'logout') {
	isetcookie('_userid', "",-1);
	isetcookie('siteuniacid',"",-1);
	isetcookie('siteroot',"",-1);
	message("退出成功",$this->createMobileUrl('login'),'success');
	
} elseif ($operation == 'changepassword') {
	$opass=md5($_GPC['opass']);
	$newpass=md5($_GPC['newpass']);
	if($user['password']!=$opass)die(json_encode(array('success'=>false,'msg'=>"原密码错误")));
	pdo_update('j_hmoney_user',array('password'=>$newpass),array('id'=>$user['id']));
	die(json_encode(array('success'=>true)));
	
	
} elseif ($operation == 'getpcategood') {
	$pcate=intval($_GPC['pcate']);
	$goodslist=array();
	if($pcate==-1){
		$list=pdo_fetchall("SELECT * FROM ".tablename('j_hmoney_goodmarket') . " WHERE groupid=:a and status=1 and starttime<=:b and endtime>=:b and contentid<>'' order by id desc",array(":a"=>$shopid,":b"=>TIMESTAMP));
		foreach($list as $row){
			if($row['limitweek']){
				$day=date('w') ? date('w') : 7;
				if(!in_array($day,explode(',',$row['limitweek'])))continue;
			}
			if($row['limithour']){
				$time=intval(date('h'));
				if(!in_array($time,explode(',',$row['limithour'])))continue;
			}
			$goods=pdo_fetchall("SELECT * FROM ".tablename('j_hmoney_goods')." WHERE id in(".$row['contentid'].") and status=1 and store<>0 order by id desc");
			for($i=0;$i<count($goods);$i++){
				$temp=$goods[$i];
				if(strpos($row['discount'],"%")){
					$temp['title']="[".(str_replace("%","",$row['discount'])*0.1)."折]".$goods[$i]['title'];
					$temp['marketprice']=$this->_2money($goods[$i]['marketprice']*(str_replace("%","",$row['discount'])));
				}
				if(strpos($row['discount'],"-")!==false){
					if($goods[$i]['marketprice']-abs($row['discount'])>=0){
						$temp['title']="[".(str_replace("-","立减",$row['discount']))."]".$goods[$i]['title'];
						$temp['marketprice']=$this->_2money(($goods[$i]['marketprice']-abs($row['discount']))*100);
					}
					
				}
				array_push($goodslist,$temp);
			}
		}
	}else{
		$goodslist=pdo_fetchall("SELECT * FROM " . tablename('j_hmoney_goods') . " WHERE weid = '".$_W['uniacid']."' and pcate=:a and groupid=:b and status=1 and store<>0 order by displayorder asc,id asc",array(":a"=>$pcate,":b"=>$shopid));
	}
	for($i=0;$i<count($goodslist);$i++){
		if(!$goodslist[$i]['thumb'])continue;
		$goodslist[$i]['thumb']=tomedia($goodslist[$i]['thumb']);
	}
	die(json_encode(array('success'=>true,'list'=>$goodslist,"a"=>count($goods))));

} elseif ($operation == 'getgood') {
    $id=intval($_GPC['id']);
    if(!$id)die(json_encode(array('success'=>false,""=>"异常错误")));
    $goods=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_goods')." WHERE weid='".$_W['uniacid']."' and groupid=:a and id=:b",array(":a"=>$shopid,":b"=>$id));
    die(json_encode(array('success'=>true,"goods"=>$goods)));

} elseif ($operation == 'selectgood') {
	$id=intval($_GPC['id']);
	$num=intval($_GPC['num']);
	$mid=intval($_GPC['mid']);
	if(!$num || !$num)die(json_encode(array('success'=>false,""=>"异常错误")));
	$goods=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_goods')." WHERE weid='".$_W['uniacid']."' and groupid=:a and id=:b",array(":a"=>$shopid,":b"=>$id));
	if(!$goods)die(json_encode(array('success'=>false,""=>"无此商品")));
	if($mid){
		$item=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_ordergoods')." WHERE id=:b",array(":b"=>$id));
		$hnum=$item['num'];
		if($num==$hnum){
			die(json_encode(array('success'=>true)));
		}elseif($num<$hnum){
			die(json_encode(array('success'=>true)));
		}elseif($num>$hnum){
			if($num-$hnum>$goods['store']){
				die(json_encode(array('success'=>false,"msg"=>"库存不足，差【".($num-$hnum-$goods['store'])."】个")));
			}elseif($num-$hnum<=$goods['store']){
				die(json_encode(array('success'=>true)));
			}
		}
	}else{
		if(!$goods['status'])die(json_encode(array('success'=>false,"msg"=>"该商品已经下架")));
		if($goods['store']==0)die(json_encode(array('success'=>false,"msg"=>"库存不足")));
		if($goods['store']<0)die(json_encode(array('success'=>true)));
		if($num>$goods['store'])die(json_encode(array('success'=>false,"msg"=>"库存不足，差【".$num-$goods['store']."】个")));
		die(json_encode(array('success'=>true)));
	}
} elseif ($operation == 'sendmemberpaycode') {
	$memberid=$_GPC["memberid"];
	$orderid=$_GPC["orderid"];
	$code=mt_rand(1000,9999);
	$member=pdo_fetch("SELECT openid FROM ".tablename('j_hmoney_membercard')." WHERE weid = '".$_W['uniacid']."' and id=:a ",array(":a"=>$memberid));
	if(!$member["openid"])die(json_encode(array('success'=>true,'need'=>false,"code"=>$code)));
	if(!$cfg["tempmsg_paycode"])die(json_encode(array('success'=>true,'need'=>false,"code"=>$code)));
	$order=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_order')." WHERE groupid=:a and id=:b",array(":a"=>$shopid,":b"=>$orderid));
	pdo_update("j_hmoney_order",array("paycode"=>$code),array("id"=>$orderid));
	$temp=array(
		"first"=>array(
			"value"=>"尊敬的顾客",
			"color"=>"#000000"
		),
		"number"=>array(
			"value"=>$code,
			"color"=>"#FF0000"
		),
		"remark"=>array(
			"value"=>"该验证码有效期3分钟可使用1次，转发无效",
			"color"=>"#333333"
		)
	);
	$acid=pdo_fetchcolumn("SELECT acid FROM ".tablename('account')." WHERE uniacid=:uniacid ",array(':uniacid'=>$_W['uniacid']));
	$acc = WeAccount::create($acid);
	$acc->sendTplNotice($member['openid'],$cfg["tempmsg_paycode"],$temp,"","#FF0000");
	die(json_encode(array('success'=>true,'need'=>true,"code"=>$code)));

} elseif ($operation == 'searchgood') {
	$keyword=trim($_GPC['keyword']);
	if(!$keyword)die(json_encode(array('success'=>false,'goods'=>"无此商品")));
	$sql=" and goodsn='".$keyword."' ";
	$pattern="/^[a-zA-Z\s]+$/";
	if(preg_match($pattern, strtolower($keyword))){
		$sql=" and shorttitle='".$keyword."' ";
	}
	$goods=pdo_fetch("SELECT * FROM " . tablename('j_hmoney_goods') . " WHERE weid = '".$_W['uniacid']."' and groupid=:a $sql order by displayorder asc,id asc limit 1",array(":a"=>$shopid));
	if(!$goods){
		if(strlen($keyword)<6 || strpos($keyword,".")){
			$goods=array(
				"marketprice"=>$this->_2money(($keyword*100)),
				"memberprice"=>0,
				"title"=>'',
				"goodsn"=>'',
				"id"=>0,
			);
		}
	}
	die(json_encode(array('success'=>true,'goods'=>$goods)));
	
} elseif ($operation == 'fastgood') {
	$keyword=trim($_GPC['keyword']);
	if(!$keyword)die(json_encode(array('success'=>false,'msg'=>"无此商品")));
	$sql=" and goodsn='".$keyword."' ";
	$pattern="/^[a-zA-Z\s]+$/";
	if(preg_match($pattern, strtolower($keyword))){
		$sql=" and left(shorttitle,".strlen($keyword).") = '".$keyword."' ";
	}
	$goods=pdo_fetchall("SELECT * FROM ".tablename('j_hmoney_goods')." WHERE weid = '".$_W['uniacid']."' and groupid=".$shopid." $sql order by id desc ");
	if($goods){
		for($i=0;$i<count($goods);$i++){
			$goods[$i]['thumb']=tomedia($goods[$i]['thumb']);
		}
	}
	die(json_encode(array('success'=>true,'goods'=>$goods)));
	
	
} elseif ($operation == 'postneworder') {
	$orderid=$_GPC["orderid"];
	if(!$orderid){
		$orderDisplayorder=pdo_fetchcolumn("SELECT max(CONVERT(`serialnum`,SIGNED))  FROM " . tablename('j_hmoney_order') . " WHERE weid=:c and groupid=:a and createdate=:b ",array(":a"=>$shopid,":b"=>date("Y-m-d"),":c"=>$_W['uniacid']));
		$orderDisplayorder=$orderDisplayorder+1;
		if(strlen($orderDisplayorder)<4){
			$temp="";
			for($i=0;$i<4-strlen($orderDisplayorder);$i++){
				$temp.="0";
			}
			$orderDisplayorder=$temp.$orderDisplayorder;
		}
		$data=array(
			"weid"=>$_W['uniacid'],
			"groupid"=>$shopid,
			"userid"=>$userid,
			"serialnum"=>$orderDisplayorder,
			"out_trade_no"=>TIMESTAMP.mt_rand(100,999),
			"createtime"=>TIMESTAMP,
			"createdate"=>date("Y-m-d"),
		);
		pdo_insert("j_hmoney_order",$data);
		$orderid=pdo_insertid();
		$trade=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_order')." WHERE weid = '".$_W['uniacid']."' and id=:a ",array(":a"=>$orderid));
		die(json_encode(array('success'=>true,'trade'=>$trade)));
	}else{
		$trade=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_order')." WHERE weid = '".$_W['uniacid']."' and id=:a ",array(":a"=>$orderid));
		$goodlist=pdo_fetchall("SELECT a.*,b.unitname,b.marketprice FROM ".tablename('j_hmoney_ordergoods')." as a LEFT JOIN ".tablename('j_hmoney_goods')." as b ON a.goodid=b.id  WHERE a.orderid=:a order by a.id desc ",array(":a"=>$trade['id']));
		die(json_encode(array('success'=>true,'trade'=>$trade,'goods'=>$goodlist)));
	}
	
	
} elseif ($operation == 'submitorder') {
	$orderid=$_GPC["orderid"];
	$param=$_GPC["param"];
	if(!$orderid)die(json_encode(array('success'=>false,'msg'=>"订单编号不能为空")));
	$trade=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_order')." WHERE weid = '".$_W['uniacid']."' and id=:a ",array(":a"=>$orderid));
	$sqlinsert="insert into ".tablename('j_hmoney_ordergoods')." (weid,groupid,orderid,createtime,out_trade_no,goodid,goodsn,title,price,oldprice,num,total_fee,taste)VALUES";
	$tempInsertAry=array();
	$tempUpdateAry=array();
	$goodisAry=array();
	$goodNewisAry=array();
	$MidAry=array();
	$MidNewAry=array();
	$itemlist=pdo_fetchall("SELECT id,goodid,num FROM ".tablename('j_hmoney_ordergoods')." WHERE orderid = :a ",array(":a"=>$orderid));
	
	foreach($itemlist as $row){
		$MidAry[$row['id']]=$row['num'];
		if(!isset($goodisAry[$row['goodid']]))$goodisAry[$row['goodid']]=0;
		$goodisAry[$row['goodid']]=$goodisAry[$row['goodid']]+$row['num'];
	}
	$isnewgood=false;
	foreach($param as $row){
		//id+"|"+goodid+"|"+goodsn+"|"+title+"|"+price+"|"+mprice+"|"+oprice+"|"+num+"|"+fee+ispack+taste
		$tempAry=explode("|",$row);
		$num+=$tempAry[7];
		if($goodNewisAry[$tempAry[1]]==NULL){
			$goodNewisAry[$tempAry[1]]=$tempAry[7];
		}else{
			$goodNewisAry[$tempAry[1]]=$tempAry[7]+$goodNewisAry[$tempAry[1]];
		}
		if($tempAry[0]=="undefined"){
			$isnewgood=true;
			$tempInsertAry[]="('".implode("','",array($_W["uniacid"],$shopid,$orderid,TIMESTAMP,$trade['out_trade_no'],$tempAry[1],$tempAry[2],$tempAry[3],$tempAry[4],$tempAry[6],$tempAry[7],bcmul($tempAry[8],100,0),$tempAry[10]))."')";
		}else{
			$MidNewAry[$tempAry[0]]=$tempAry[7];
			$tempUpdateAry[$tempAry[0]]=array(
				"price"=>$tempAry[4],
				"num"=>$tempAry[7],
				"fee"=>bcmul($tempAry[8],100,0),
			);
		}
	}
	//--计算数量--//
	unset($goodisAry[0]);
	if(count($goodNewisAry)){
		$goodataAry=array();
		$goodlist=pdo_fetchall("SELECT id,store,title FROM ".tablename('j_hmoney_goods')." WHERE id in (".implode(",",array_keys($goodNewisAry)).") and store>-1 ");
		foreach($goodlist as $row){
			if($row['store']-($goodNewisAry[$row['id']]-$goodisAry[$row['id']])<0){
				die(json_encode(array('success'=>false,'msg'=>"【".$row['title']."】库存不足,差【".abs($row['store']-$goodisAry[$row['id']])."】")));
				break;
			}
			$goodataAry[$row['id']]=$row['store']-($goodNewisAry[$row['id']]-$goodisAry[$row['id']]);
		}
	}
	$sql=count($tempInsertAry) ? $sqlinsert.implode(",",$tempInsertAry).";":"";
	pdo_run($sql);
	foreach($MidAry as $index=>$row){
		if(isset($MidNewAry[$index]))unset($MidAry[$index]);
	}
	if(count($MidAry))pdo_delete("j_hmoney_ordergoods"," id in (".implode(",",array_keys($MidAry)).")");
	if(count($tempUpdateAry)){
		foreach($tempUpdateAry as $index=>$row){
			pdo_update("j_hmoney_ordergoods",array(
				"price"=>$row['price'],
				"num"=>$row['num'],
				"total_fee"=>$row['fee'],
			),array("id"=>$index));
		}
	}
	if(count($goodataAry)){
		foreach($goodataAry as $index=>$row){
			pdo_update("j_hmoney_goods",array("store"=>$row),array("id"=>$index));
		}
	}
	$gather=pdo_fetch("SELECT sum(num) as num1,count(*) as num2,sum(total_fee) as tfee,sum(oldprice*num*100) as ofee FROM " . tablename('j_hmoney_ordergoods') . " WHERE weid = '".$_W['uniacid']."' and orderid=:a ",array(":a"=>$trade['id']));
	$data=array(
		"order_fee"=>$gather['tfee'],
		"total_fee"=>$gather['tfee'],
		"num"=>$gather['num1'],
		"species"=>$gather['num2'],
		"memberno"=>$_GPC['memberid']
	);
	pdo_update("j_hmoney_order",$data,array("id"=>$orderid));
	die(json_encode(array('success'=>true)));
	
	
} elseif ($operation == 'clearorder') {
	$orderid=$_GPC["orderid"];
	$trade=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_order')." WHERE id=:a",array(":a"=>$orderid));
	if($trade['status'] || !$trade)die(json_encode(array('success'=>false,'msg'=>"该订单不能删除")));
	pdo_delete('j_hmoney_order',array('id'=>$trade['id']));
	$goodlist=pdo_fetchall("SELECT * FROM " . tablename('j_hmoney_ordergoods') . " WHERE orderid=:a ",array(":a"=>$orderid));
	if($goodlist){
		foreach($goodlist as $row){
			$store=pdo_fetchcolumn("SELECT store FROM ".tablename('j_hmoney_goods')." WHERE id=:a",array(":a"=>$row['goodid']));
			if($store!=-1){
				pdo_update("j_hmoney_goods",array("store"=>$store+$row['num']),array("id"=>$row['goodid']));
			}
			pdo_delete('j_hmoney_ordergoods',array('id'=>$row['id']));
		}
	}
	die(json_encode(array('success'=>true)));
	
} elseif ($operation == 'getorderdetail') {	
	$orderid=$_GPC["orderid"];
	$trade=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_order')." WHERE weid = '".$_W['uniacid']."' and id=:a ",array(":a"=>$orderid));
	$goodlist=pdo_fetchall("SELECT a.*,b.unitname,b.marketprice FROM ".tablename('j_hmoney_ordergoods')." as a LEFT JOIN ".tablename('j_hmoney_goods')." as b ON a.goodid=b.id  WHERE a.orderid=:a order by a.id desc ",array(":a"=>$trade['id']));
	die(json_encode(array('success'=>true,'trade'=>$trade,'goods'=>$goodlist)));

	
} elseif ($operation == 'getorder') {	
	$orderid=$_GPC["orderid"];
	$trade=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_order')." WHERE weid = '".$_W['uniacid']."' and id=:a ",array(":a"=>$orderid));
	if($trade['memberno']){
		$member=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_membercard')." WHERE weid = '".$_W['uniacid']."' and id=:a ",array(":a"=>$trade['memberno']));
		$trade['membercardno']=$member["cardno"];
	}
	$market=$this->findMarketing($trade['order_fee'],$shopid,1);
	die(json_encode(array('success'=>true,'trade'=>$trade,'market'=>$market)));
	
} elseif ($operation == 'checkcoupon') {
	$code=$_GPC['code'];
	if(!$code)die(json_encode(array("success"=>false,"msg"=>"卡券ID不能为空")));
	load()->func('communication');
	$acid=pdo_fetchcolumn("SELECT acid FROM ".tablename('account')." WHERE uniacid=:uniacid ",array(':uniacid'=>$_W['uniacid']));
	$acc = WeAccount::create($acid);
	$tokens=$acc->fetch_token();
	$pageparama=json_encode(array("code"=>$code));
	$resp = ihttp_request("https://api.weixin.qq.com/card/code/get?access_token=".$tokens,$pageparama, $xml);
	if(is_error($resp))$procResult = $resp;
	$result=@json_decode($resp['content'],true);
	if($result['errcode'])die(json_encode(array("success"=>false,"msg"=>"卡券查询失败，原因：".$result['errmsg'])));
	$cardid=$result['card']['card_id'];
	$begin_time=$result['card']['begin_time'];
	$end_time=$result['card']['end_time'];
	$can_consume=$result['can_consume'];
	$user_card_status=$result['user_card_status'];
	$openid=$result['openid'];
	if($begin_time>TIMESTAMP || $end_time<TIMESTAMP)die(json_encode(array("success"=>false,"msg"=>"该卡券不可用，原因：该卡券使用时间为：".date("Y-m-d H:i",$begin_time)."-".date("Y-m-d H:i",$end_time))));
	$cardstatus=array(
		"CONSUMED"=>"已使用",
		"EXPIRE"=>"已过期",
		"GIFT_TIMEOUT"=>"转赠超时",
		"DELETE"=>"已删除",
		"UNAVAILABLE"=>"已失效",
		"invalid serial code"=>"已被朋友使用",
	);
	if(!$can_consume){
		die(json_encode(array("success"=>false,"msg"=>$cardstatus[$user_card_status])));
	}
	$pageparama=json_encode(array("card_id"=>$cardid));
	$resp = ihttp_request("https://api.weixin.qq.com/card/get?access_token=".$tokens,$pageparama, $xml);
	if(is_error($resp))die(json_encode(array("success"=>false,"msg"=>$resp)));
	$cardinfo=@json_decode($resp['content'],true);
	$coupon=array();
	$coupon['type']=strtolower($cardinfo['card']['card_type']);
	switch($coupon['type']){
		case "discount":
			$coupon["typestr"]="折扣券";
			$coupon["discount"]=$cardinfo['card']['discount']['discount'];
			$coupon["msg"]=$coupon["discount"]."%";
		break;
		case "cash":
			$coupon["typestr"]="代金券";
			$coupon["least_cost"]=isset($cardinfo['card']['cash']['least_cost']) ? $cardinfo['card']['cash']['least_cost'] : 0;
			$coupon["discount"]=$cardinfo['card']['cash']['reduce_cost'];
			$coupon["msg"]=$coupon["least_cost"] ? "满".$this->_2money(($coupon["least_cost"]))."元减".$this->_2money(($coupon["discount"]))."元": "直减".$this->_2money(($coupon["discount"]))."元";
		break;
		case "gift":
			$coupon["typestr"]="礼品券";
			$coupon["msg"]=$cardinfo['card']['gift']['gift'];
		break;
		case "groupon":
			$coupon["typestr"]="团购券";
			$coupon["msg"]=$cardinfo['card']['groupon']['deal_detail'];
		break;
		case "general_coupon":
			$coupon["typestr"]="优惠券";
			$coupon["msg"]=$cardinfo['card']['general_coupon']['default_detail'];
		break;
	}
	$coupon['openid']=$openid;
	$coupon['code']=$code;
	die(json_encode(array("success"=>true,"cardinfo"=>$coupon)));
	
} elseif ($operation == 'getmember') {
	if(!$_GPC['memberid']){
		$keyword=trim($_GPC['keyword']);
		if(!$keyword)die(json_encode(array('success'=>false,'msg'=>"请输入关键字")));
		$condition = "  and (cardno =:a or wxcardno=:a or mobile=:a) ";
		$member=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_membercard')." WHERE weid = '".$_W['uniacid']."' $condition ",array(":a"=>$keyword));
	}else{
		$member=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_membercard')." WHERE weid = '".$_W['uniacid']."' and id=:a ",array(":a"=>$_GPC['memberid']));
	}
	if(!$member)die(json_encode(array('success'=>false,'msg'=>"无此会员")));
	$cost=pdo_fetchcolumn("SELECT sum(cash) FROM " . tablename('j_hmoney_recharge') . " WHERE weid = '".$_W['uniacid']."' and cid=:a and status=1 ",array(":a"=>$member['id']));
	$member['cash2']=$member['cash'];
	$member['bird']=$member['birdday'] ? date("m-d",strtotime($member['birdday'])) : "-";
	$groupAry=array();
	foreach(mc_groups() as $row){
		$groupAry[$row['groupid']]=$row['title'];
	}
	$member['credit2']=$member['credit'];
	$member['level']=$groupAry[$member['gid']];
	if($member['uid'] || $member['openid']){
		$uid=$member['uid'];
		if(!$uid)$uid=mc_openid2uid($member['openid']);
		$memberuser=mc_fetch($uid);
		
		if($cfg['isgeneralbalance'])$member['cash2']=$member['cash2']+bcmul($memberuser['credit2'],100,0);
		$member['credit2']=$member['credit']+$memberuser['credit1'];
	}
	$member['cash2']=$this->_2money(($member['cash2']));
	$orderid=$_GPC["orderid"];
	$trade=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_order')." WHERE weid = '".$_W['uniacid']."' and id=:a ",array(":a"=>$orderid));
	$market=$this->findMarketing($trade['order_fee'],$shopid,1,$member['id']);
	die(json_encode(array('success'=>true,'member'=>$member,'market'=>$market,'cost'=>$this->_2money(($cost)))));
	
} elseif ($operation == 'payall') {
	$orderid=intval($_GPC['orderid']);
	if(!$orderid)die(json_encode(array('success'=>false,"msg"=>"订单号不能为空")));
	$trade=pdo_fetch("SELECT * FROM " . tablename('j_hmoney_order') . " WHERE id =:a",array(":a"=>$orderid));
	if($trade['ispay']>0)die(json_encode(array('success'=>false,"msg"=>"已经支付的订单不能再支付")));
	//<!--0无优惠,1系统满减，2手动折扣，3优惠券，-->
	$data=array(
		"total_fee"=>intval($_GPC["totalfee"]*100),
		"paid_fee"=>intval($_GPC["totalfee"]*100),
		"discount"=>$_GPC["discount"],
		"discount_fee"=>intval($_GPC["coupon"]*100),
		"discounttype"=>$_GPC["coupontype"],
		"couponid"=>$_GPC["couponno"],
		"memberno"=>$_GPC["memberid"],
		"paytype"=>$_GPC["paytype"],
        "paytype2"=>$_GPC["paytype2"],
		"remark"=>$_GPC["remark"],
		"marketing"=>$_GPC["marketing"],
        "change_fee"=>bcmul($_GPC["change"],100,0),
//		"paycode"=>$_GPC["paycode"],
		"paid_fee1"=>intval($_GPC["paidfee"]*100),
		"paid_fee2"=>intval($_GPC["paidfee2"]*100),
	);
    if($data['paid_fee1']+$data['paid_fee2']>$data['total_fee']){
        if($data["paytype"]==2){
            $data['paid_fee1']=$data['total_fee']-$data['paid_fee2'];
        }
        if($data["paytype2"]==2){
            $data['paid_fee2']=$data['total_fee']-$data['paid_fee1'];
        }
    }
	/*处理优惠*/
	if($data['couponid']){
		$employCard=$this->employCard($data['couponid'],$shopid);
		if(!$employCard || !$employCard['success'])die(json_encode(array('success'=>false,"msg"=>$employCard['msg'])));
	}
	if(!$data['paid_fee2']){
		$data['paytype2']=-1;
		$data['pay2_status']=1;
	}
    pdo_update("j_hmoney_order",$data,array("id"=>$orderid));
	/*实际支付流程*/
	if($data["paytype"]>4 || $data["paytype2"]>4){
		$data['ispay']=1;
		$data['time_end']=TIMESTAMP;
		if($data["paytype"]>4)$data["pay1_status"]=1;
		if($data["paytype2"]>4)$data["pay2_status"]=1;
	}
	if($data["paytype"]==2 || $data["paytype2"]==2){
		$data['ispay']=1;
		$data['time_end']=TIMESTAMP;
		if($data["paytype"]==2)$data["pay1_status"]=1;
		if($data["paytype2"]==2)$data["pay2_status"]=1;
	}
	if($data["paytype"]==3 || $data["paytype2"]==3){
		$data['ispay']=1;
		$data['time_end']=TIMESTAMP;
		$data['remark']=$data['remark'].";银行卡".$_GPC["code"];
		if($data["paytype"]==3)$data["pay1_status"]=1;
		if($data["paytype2"]==3)$data["pay2_status"]=1;
	}
	if($data["paytype"]==4 || $data["paytype2"]==4){
		if(!$data["memberno"])die(json_encode(array('success'=>false,"msg"=>"会员卡不能为空")));
		$member=pdo_fetch("SELECT * FROM " . tablename('j_hmoney_membercard') . " WHERE weid = '".$_W['uniacid']."' and id=:a ",array(":a"=>$data["memberno"]));
		if(!$member)die(json_encode(array('success'=>false,"msg"=>"会员数据错误")));
        if($cfg['ispaycode']){
            if(!$_GPC['paycode'])die(json_encode(array('success'=>false,"msg"=>"验证码不能为空")));
            if($_GPC['paycode']!=$trade["paycode"])die(json_encode(array('success'=>false,"msg"=>"验证码错误")));
        }
		$membercash=$member['cash'];
		$isGeneral=0;
		if($member['openid'] && $cfg['isgeneralbalance']){
			if($member['cash'])$this->transferBalance($member['id']);
			$uid=$member['uid'];
			if(!$uid)$uid=mc_openid2uid($member['openid']);
			$memberinfo=mc_fetch($uid);
			$membercash=intval($memberinfo["credit2"]*100);
			$isGeneral=1;
		}
		$payfee=$data["paytype"]==4 ? $data["paid_fee1"] : $data["paid_fee2"];
		if($membercash<$payfee)die(json_encode(array('success'=>false,"msg"=>"余额不足")));
		if($isGeneral){
			mc_credit_update($uid,"credit2",$this->_2money(($payfee))*(-1),array("","收银系统支付￥".$this->_2money(($payfee))."元"));
		}else{
			pdo_update("j_hmoney_membercard",array('cash'=>$member['cash']-$payfee),array("id"=>$member['id']));
		}
		$this->memberCardInform($data["memberno"]);
		$data['ispay']=1;
		$data['time_end']=TIMESTAMP;
		if($data["paytype"]==4)$data["pay1_status"]=1;
		if($data["paytype2"]==4)$data["pay2_status"]=1;
		$memberdata=array(
			"weid"=>$_W["uniacid"],
			"cid"=>$member['id'],
			"userid"=>$userid,
			"groupid"=>$shopid,
			"usetype"=>1,
			"paytype"=>-1,
			"startfee"=>$membercash,
			"cash"=>$payfee,
			"endfee"=>$membercash-$payfee,
			"out_trade_no"=>$trade["out_trade_no"],
			"status"=>1,
			"createtime"=>TIMESTAMP,
			"createdate"=>date("Y-m-d"),
		);
		pdo_insert("j_hmoney_recharge",$memberdata);
	}
	if($data["paytype"]==0 || $data["paytype2"]==0){
		$qrcode=$_GPC['qrcode'];
		$payfee= $data["paytype"]==0 ? $data["paid_fee1"] : $data["paid_fee2"];
		if($cfg['isbank']){
			$bank_trade_no=TIMESTAMP.mt_rand(1000,9999);
			pdo_update("j_hmoney_order",array('bank_trade_no'=>$bank_trade_no),array("id"=>$orderid));
			$result=Bankpay_micropay($cfg,$payfee,$bank_trade_no,$trade['out_trade_no'],$qrcode,$userid,$shopid);
            if(isset($result["success"]) && $result["success"]==false){
                die(json_encode(array("success"=>false,"msg"=>$result['msg'])));
            }
			if($result['status'] || $result['result_code']){
				if($result['err_code']=='10003' || $result['err_code']=='USERPAYING'){
					die(json_encode(array("success"=>true,"paywait"=>true,"orderid"=>$orderid)));
				}
				die(json_encode(array("success"=>false,"msg"=>$result['message'].$result['err_msg'])));
			}
			$data["openid"]=$result['sub_openid'];
			$data["cash_fee"]=$result['total_fee'];
			$data["transaction_id"]=$result['out_transaction_id'];
			$data["time_end"]=strtotime($result['time_end']);
			$data["ispay"]=1;
        }elseif($cfg['isymf']){
            $payfee1=$this->_2money($payfee);
            $result=ymf_micropay($qrcode,$payfee1,$trade["id"],$cfg);
            if($result['success']){
                $data["bank_trade_no"]=$result['orderno'];
                $data["openid"]=$result['uuid'];
                $data["cash_fee"]=intval($result['money']*100);
                $data["transaction_id"]=$result['transid'];
                $data["time_end"]=strtotime($result['paytime']);
                $data["ispay"]=1;
            }else{
                die(json_encode(array("success"=>false,"msg"=>$result['msg'])));
            }
		} else{
			$payParama=array(
				"appid"=>$shop['appid'] ? $shop['appid'] : $cfg['appid'],
				"pay_mchid"=>strval($shop['pay_mchid']) ? strval($shop['pay_mchid']) : strval($cfg['pay_mchid']),
				"pay_signkey"=>$shop['pay_signkey'] ? $shop['pay_signkey'] : $cfg['pay_signkey'],
				"outTradeNo"=>strval($trade['out_trade_no']),
				"pay_ip"=>$shop['pay_ip'] ? $shop['pay_ip'] : $cfg['pay_ip'],
				"sub_appid"=>$shop['sub_appid'] ? $shop['sub_appid'] : $cfg['sub_appid'],
				"sub_mch_id"=>$shop['sub_mch_id'] ? $shop['sub_mch_id'] : $cfg['sub_mch_id'],
			);
			$pay_signkey=trim($shop['pay_signkey']) ? trim($shop['pay_signkey']) : trim($cfg['pay_signkey']);
			$pageparama=array(
				"appid"=>$payParama['appid'],
				"mch_id"=>strval($shop['pay_mchid']) ? strval($shop['pay_mchid']) : strval($cfg['pay_mchid']),
				"device_info"=>$deviceinfo,
				"nonce_str"=>getNonceStr(),
				"body"=>$shop['companyname'],
				"detail"=>$shop['companyname'],
				"attach"=>"-",
				"out_trade_no"=>$payParama['outTradeNo'],
				"total_fee"=>$payfee,
				"fee_type"=>"CNY",
				"spbill_create_ip"=>$shop['pay_ip'] ? $shop['pay_ip'] : $cfg['pay_ip'],
				"goods_tag"=>"000001",
				"auth_code"=>$qrcode,
			);
			if($payParama['sub_appid'])$pageparama['sub_appid']=$payParama['sub_appid'];
			if($payParama['sub_mch_id'])$pageparama['sub_mch_id']=$payParama['sub_mch_id'];
			$sign=MakeSign($pageparama,$pay_signkey);
			$pageparama['sign']=$sign;
			$xml = ToXml($pageparama);
			$response =postXmlCurl($xml, "https://api.mch.weixin.qq.com/pay/micropay", 10);
			$result=FromXml($response);
			if($result['result_code']!='SUCCESS'){
				if($result['err_code']=='USERPAYING'){
					die(json_encode(array("success"=>true,"paywait"=>true,"orderid"=>$orderid)));
				}elseif($result['err_code']=='INVALID_REQUEST'){
                    if($result['err_code_des']==201){
                        $neworderno=TIMESTAMP.mt_rand(1,999);
                        pdo_update("j_hmoney_order",array("out_trade_no"=>$neworderno),array("id"=>$orderid));
                        pdo_update("j_hmoney_ordergoods",array("out_trade_no"=>$neworderno),array("orderid"=>$orderid));
                        die(json_encode(array("success"=>false,"msg"=>"支付单号重复，请再次提交")));
                    }
                }
				die(json_encode(array("success"=>false,"msg"=>$result['err_code_des'].$result['return_msg'])));
			}
			$data["openid"]=$result['openid'];
			$data["cash_fee"]=$result['cash_fee'];
			$data["coupon_fee"]=$result['coupon_fee'];
			$data["transaction_id"]=$result['transaction_id'];
			$data["time_end"]=strtotime($result['time_end']);
			$data["ispay"]=1;
		}
		if($data["paytype"]==0)$data["pay1_status"]=1;
		if($data["paytype2"]==0)$data["pay2_status"]=1;
	}
	if($data["paytype"]==1 || $data["paytype2"]==1){
		$qrcode=$_GPC['qrcode'];
		$payfee= $data["paytype"]==1 ? $data["paid_fee1"] : $data["paid_fee2"];
		if($cfg['isbank']){
			$bank_trade_no=TIMESTAMP.mt_rand(1000,9999);
			pdo_update("j_hmoney_order",array('bank_trade_no'=>$bank_trade_no),array("id"=>$orderid));
			$result=Bankpay_micropay($cfg,$payfee,$bank_trade_no,$trade['out_trade_no'],$qrcode,$userid,$shopid);
            if(isset($result["success"]) && $result["success"]==false){
                die(json_encode(array("success"=>false,"msg"=>$result['msg'])));
            }
			if($result['status'] || $result['result_code']){
				if($result['err_code']=='10003' || $result['err_code']=='USERPAYING'){
					die(json_encode(array("success"=>true,"paywait"=>true,"orderid"=>$orderid)));
				}
				die(json_encode(array("success"=>false,"msg"=>$result['message'].$result['err_msg'])));
			}
			$data["openid"]=$result['sub_openid'];
			$data["cash_fee"]=$result['total_fee'];
			$data["transaction_id"]=$result['out_transaction_id'];
			$data["time_end"]=strtotime($result['time_end']);
			$data["ispay"]=1;
        }elseif($cfg['isymf']){
            $payfee1=$this->_2money($payfee);
            $result=ymf_micropay($qrcode,$payfee1,$trade["id"],$cfg);
            if($result['success']){
                $data["bank_trade_no"]=$result['orderno'];
                $data["openid"]=$result['uuid'];
                $data["cash_fee"]=intval($result['money']*100);
                $data["transaction_id"]=$result['transid'];
                $data["time_end"]=strtotime($result['paytime']);
                $data["ispay"]=1;
            }else{
                die(json_encode(array("success"=>false,"msg"=>$result['msg'])));
            }
		}else{
			$payParama=array(
				"app_id"=>$shop['app_id'] ? $shop['app_id'] : $cfg['app_id'],
				"outTradeNo"=>strval($trade['out_trade_no']),
				"appauthtoken"=>$shop['appauthtoken'] ? $shop['appauthtoken'] : $cfg['appauthtoken'],
				"alipay_cert"=>$cfg['alipay_cert'],
				"alipay_key"=>$cfg['alipay_key'],
				"alipay_store_id"=>$shop['alipay_store_id'] ,
				"alipid"=>$shop['alipid'] ? $shop['alipid'] : $cfg['alipid'] ,
			);
			$total_amount = $data['total_fee'];
			$postfee=$this->_2money(($payfee));
			require_once '../addons/j_hmoney/plug/plug_alipay/F2fpay.php';
			$f2fpay = new F2fpay();
			$response = $f2fpay->barpay($payParama['outTradeNo'],$qrcode,$postfee,$shop['companyname'],$payParama);
			$temp=(array)$response;
			$result=(array)$temp['alipay_trade_pay_response'];
			if($result['code']=="10003"){
				die(json_encode(array("success"=>true,"paywait"=>true,"orderid"=>$orderid)));
			}elseif($result['code']=="10000"){
				$data["transaction_id"]=$result['trade_no'];
				$data["cash_fee"]=intval($result['receipt_amount']*100);
				$data["time_end"]=strtotime($result['gmt_payment']);
				$data["ispay"]=1;
			}else{
				die(json_encode(array("success"=>false,"msg"=>$result['sub_msg'],"aa"=>$payParama)));
			}
		}
		if($data["paytype"]==1)$data["pay1_status"]=1;
		if($data["paytype2"]==1)$data["pay2_status"]=1;
	}

    $data["status"]=2;
	pdo_update("j_hmoney_order",$data,array("id"=>$orderid));
	pdo_update("j_hmoney_ordergoods",array('ispay'=>1,'status'=>2),array("orderid"=>$orderid));
	die(json_encode(array('success'=>true)));
	
} elseif ($operation == 'paywaitpassword') {
	$orderid=intval($_GPC['orderid']);
	if(!$orderid)die(json_encode(array('success'=>false,"msg"=>"订单号不能为空")));
	$trade=pdo_fetch("SELECT * FROM " . tablename('j_hmoney_order') . " WHERE id =:a",array(":a"=>$orderid));
	if($trade['ispay']==1)die(json_encode(array('success'=>false,"msg"=>"已经支付的订单不能再支付")));
	if($cfg['isbank']){
			$result=Bankpay_checkpay($cfg,$trade['bank_trade_no']);
			if(!$result['status'] && !$result['result_code']){
				if($result['trade_state']=='USERPAYING' || $result['trade_state']=='10003'){
					die(json_encode(array("success"=>true,"paywait"=>true,"orderid"=>$orderid)));
				}elseif($result['trade_state']=='SUCCESS'){
					$data=array(
						"openid"=>$result['sub_openid'],
						"ispay"=>1,
                        "status"=>2,
						"cash_fee"=>intval($result['total_fee']),
						"transaction_id"=>$result['out_transaction_id'],
						"time_end"=>strtotime($result['time_end']),
					);
                    if($result['trade_type']=="pay.weixin.micropay"){
                        if($trade["paytype"]==0)$data["pay1_status"]=1;
                        if($trade["paytype2"]==0)$data["pay2_status"]=1;
                    }else{
                        if($trade["paytype"]==1)$data["pay1_status"]=1;
                        if($trade["paytype2"]==1)$data["pay2_status"]=1;
                    }
					pdo_update("j_hmoney_order",$data,array("id"=>$trade['id']));
					pdo_update("j_hmoney_ordergoods",array('ispay'=>1),array("orderid"=>$trade['id']));
					die(json_encode(array("success"=>true,"paywait"=>false,"isnew"=>false,"out_trade_no"=>$trade['out_trade_no'])));
				}
				die(json_encode(array("success"=>false,"msg"=>$result['trade_state'])));
			}
			die(json_encode(array("success"=>false,"msg"=>$result['message'].$result['err_msg'])));
			
		}else{
			load()->func('communication');
			if($trade['paytype']==0){
				$payParama=array(
					"appid"=>$shop['appid'] ? $shop['appid'] : $cfg['appid'],
					"pay_mchid"=>strval($shop['pay_mchid']) ? strval($shop['pay_mchid']) : strval($cfg['pay_mchid']),
					"pay_signkey"=>$shop['pay_signkey'] ? $shop['pay_signkey'] : $cfg['pay_signkey'],
					"outTradeNo"=>strval($trade['out_trade_no']),
					"pay_ip"=>$shop['pay_ip'] ? $shop['pay_ip'] : $cfg['pay_ip'],
					"sub_appid"=>$shop['sub_appid'] ? $shop['sub_appid'] : $cfg['sub_appid'],
					"sub_mch_id"=>$shop['sub_mch_id'] ? $shop['sub_mch_id'] : $cfg['sub_mch_id'],
				);
				$pageparama=array(
					"appid"=>$payParama['appid'],
					"mch_id"=>strval($payParama['pay_mchid']),
					"out_trade_no"=>$trade['out_trade_no'],
					"nonce_str"=>getNonceStr(),
				);
				if($payParama['sub_appid'])$pageparama['sub_appid']=$payParama['sub_appid'];
				if($payParama['sub_mch_id'])$pageparama['sub_mch_id']=$payParama['sub_mch_id'];
				$sign=MakeSign($pageparama,$payParama['pay_signkey']);
				$pageparama['sign']=$sign;
				$xml = ToXml($pageparama);
				$response =postXmlCurl($xml, "https://api.mch.weixin.qq.com/pay/orderquery", 10);
				$result=FromXml($response);
				if($result['result_code']=='SUCCESS'){
					if($result['trade_state']=='USERPAYING'){
						die(json_encode(array("success"=>true,"paywait"=>true,"out_trade_no"=>$trade['out_trade_no'])));
					}elseif($result['trade_state']=='REFUND'){
						die(json_encode(array("success"=>false,"msg"=>"已退款")));
					}elseif($result['trade_state']=='NOTPAY'){
						die(json_encode(array("success"=>false,"msg"=>"没有支付")));
					}elseif($result['trade_state']=='CLOSED'){
						die(json_encode(array("success"=>false,"msg"=>"已关闭")));
					}elseif($result['trade_state']=='REVOKED'){
						die(json_encode(array("success"=>false,"msg"=>"已撤销")));
					}elseif($result['trade_state']=='PAYERROR'){
						die(json_encode(array("success"=>false,"msg"=>"支付失败(银行返回失败)")));
					}elseif($result['trade_state']=='SUCCESS'){
						$data=array(
							"openid"=>$result['openid'],
							"ispay"=>1,
                            "status"=>2,
							"coupon_fee"=>intval($result['coupon_fee']),
							"cash_fee"=>intval($result['cash_fee']),
							"transaction_id"=>$result['transaction_id'],
							"time_end"=>strtotime($result['time_end']),
						);
                        if($trade["paytype"]==0)$data["pay1_status"]=1;
                        if($trade["paytype2"]==0)$data["pay2_status"]=1;
						pdo_update("j_hmoney_order",$data,array("id"=>$trade['id']));
						pdo_update("j_hmoney_ordergoods",array('ispay'=>1),array("orderid"=>$trade['id']));
						if($trade['ispay']==0){
							die(json_encode(array("success"=>true,"paywait"=>false,"isnew"=>true,"out_trade_no"=>$trade['out_trade_no'])));
						}
						die(json_encode(array("success"=>true,"paywait"=>false,"isnew"=>false,"out_trade_no"=>$trade['out_trade_no'])));
					}
				}
				die(json_encode(array("success"=>false,"msg"=>$result['trade_state_desc'].$result['err_code_des'].$result['return_msg'])));
			}else{
				$payParama=array(
					"app_id"=>$shop['app_id'] ? $shop['app_id'] : $cfg['app_id'],
					"appauthtoken"=>$shop['appauthtoken'] ? $shop['appauthtoken'] : $cfg['appauthtoken'],
					"alipay_cert"=>$cfg['alipay_cert'],
					"alipay_key"=>$cfg['alipay_key'],
					"alipay_store_id"=>$shop['alipay_store_id'] ,
					"alipid"=>$cfg['alipid'] ,
				);
				require_once '../addons/j_hmoney/plug/plug_alipay/F2fpay.php';
				$cfg = $this->module['config'];
				$f2fpay = new F2fpay();
				$response = $f2fpay->query($out_trade_no,$payParama);
				$results=@json_decode(json_encode($response),true);
				$result=$results['alipay_trade_query_response'];
				if($result['code']==10003){
					die(json_encode(array("success"=>true,"paywait"=>true,"msg"=>"等待客户支付密码","out_trade_no"=>$trade['out_trade_no'])));
				}elseif($result['code']==10000){
					if($result['trade_status']=="TRADE_SUCCESS"){
						$data=array(
							"ispay"=>1,
                            "status"=>2,
							"transaction_id"=>$result['trade_no'],
							"cash_fee"=>intval($result['receipt_amount']*100),
							"time_end"=>strtotime($result['gmt_payment']),
						);
                        if($trade["paytype"]==1)$data["pay1_status"]=1;
                        if($trade["paytype2"]==1)$data["pay2_status"]=1;
						pdo_update("j_hmoney_order",$data,array("id"=>$trade['id']));
						pdo_update("j_hmoney_ordergoods",array('ispay'=>1),array("orderid"=>$trade['id']));
						$isnew=false;
						if($trade["ispay"]==0)$isnew=true;
						die(json_encode(array("success"=>true,"paywait"=>false,"isnew"=>$isnew,"out_trade_no"=>$trade['out_trade_no'])));
					}elseif($result['trade_status']=="WAIT_BUYER_PAY"){
						die(json_encode(array("success"=>false,"msg"=>"等待客户付款")));
					}elseif($result['trade_status']=="TRADE_CLOSED"){
						die(json_encode(array("success"=>false,"msg"=>"订单已退款")));
					}else{
						die(json_encode(array("success"=>false,"msg"=>$result['trade_status'])));
					}
				}
				die(json_encode(array("success"=>false,"msg"=>$result['sub_msg'])));
			}
		}
} elseif ($operation == 'getholdorderlist') {
	$condition.= " and groupid ='".$shopid."' ";
	$sql="SELECT * FROM " . tablename('j_hmoney_order') . " WHERE groupid ='".$shopid."' and status=0 order by id desc ";
	$list = pdo_fetchall($sql);
	die(json_encode(array('success'=>true,'list'=>$list)));
	
} elseif ($operation == 'getorderlist') {
	$datetype=intval($_GPC['datetype']);
	$keyword=trim($_GPC['keyword']);
	switch($datetype){
		case 0:
		break;
		case 1:
			$condition=" and createdate='".date("Y-m-d")."' ";
		break;
		case 2:
			$condition=" and createdate='".date("Y-m-d",strtotime('-1 day'))."' ";
		break;
		case 3:
			$condition=" and createdate>='".date("Y-m-d",strtotime('-3 day'))."' ";
		break;
		case 4:
			$condition=" and createdate>='".date("Y-m-d",strtotime('-7 day'))."' ";
		break;
		case 5:
			$condition=" and date_format(createdate,'%y-%m')='".date("y-m")."' ";
		break;
	}
	if($keyword)$condition=" and out_trade_no='".$keyword."' ";
	$condition.= " and groupid ='".$shopid."' ";
	$sql="SELECT id,out_trade_no,createtime,serialnum FROM " . tablename('j_hmoney_order') . " WHERE weid = '".$_W['uniacid']."' $condition order by id desc ";
	$list = pdo_fetchall($sql);
	
	die(json_encode(array('success'=>true,'list'=>$list)));

} elseif ($operation == 'gethistoryview') {
	$tid=$_GPC["id"];
	$order=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_order')." WHERE weid = '".$_W['uniacid']."' and id=:a",array(":a"=>$tid));
	if($order['ispay']){
		$order['paytypestr']=$order['paid_fee2'] ? _getPaytpye($order['paytype'],$shopid)."/"._getPaytpye($order['paytype2'],$shopid) :  _getPaytpye($order['paytype'],$shopid);
	}
	$goods=pdo_fetchall("SELECT * FROM " . tablename('j_hmoney_ordergoods') . " WHERE weid = '".$_W['uniacid']."' and orderid=:a order by id asc",array(":a"=>$order['id']));
	die(json_encode(array('success'=>true,'trade'=>$order,'table'=>$table,'goods'=>$goods)));
	
} elseif ($operation == 'getordergood') {
	$gid=$_GPC["id"];
	$goods=pdo_fetch("SELECT * FROM " . tablename('j_hmoney_ordergoods') . " WHERE weid = '".$_W['uniacid']."' and id=:a ",array(":a"=>$gid));
	if($goods['ispay']!=1)die(json_encode(array("success"=>false,"msg"=>"该商品不能退款")));
	$order=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_order')." WHERE weid = '".$_W['uniacid']."' and id=:a",array(":a"=>$goods['orderid']));
	$maxfee=$goods['price'];
	if($order['discount']!="100%"){
		$maxfee=$this->_2money($goods['price']*(str_replace("%","",$order['discount'])));
	}
	die(json_encode(array("success"=>true,"maxfee"=>$maxfee,"good"=>$goods,"paytype"=>$order['paytype'],"paytypestr"=>_getPaytpye($order['paytype'],$shopid))));
	
} elseif ($operation == 'getgiftlist') {
	$giftlist = pdo_fetchall("SELECT * FROM " . tablename('j_hmoney_gift') . " WHERE weid = '".$_W['uniacid']."' and groupid ='".$shopid."' order by status desc, id desc");
	die(json_encode(array("success"=>true,"list"=>$giftlist)));
	
} elseif ($operation == 'getgiftrecord') {
	$pindex = max(1, intval($_GPC['page']));
	$psize = 5;
	$condition = " and a.groupid ='".$shopid."' ";
	if($_GPC['keyword'])$condition.= " and ( a.memberid='".$_GPC['keyword'] ."' )";
	$list = pdo_fetchall("SELECT a.*,b.realname,b.cardno FROM ".tablename('j_hmoney_giftrecord')." a left join ".tablename('j_hmoney_membercard')." b on a.memberid=b.id WHERE a.weid = '".$_W['uniacid']."' $condition order by a.id desc LIMIT " . ($pindex - 1) * $psize . ',' . $psize);
	
	$total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('j_hmoney_giftrecord') . " WHERE weid = '".$_W['uniacid']."' $condition");
	$pageall= $total <= $psize ? 1 : $total % $psize ? $total / $psize+1 : $total / $psize;
	$userlist=pdo_fetchall("SELECT id,realname FROM " . tablename('j_hmoney_user') . " WHERE pcate =:a",array(":a"=>$shopid));
	$userary=array();
	foreach($userlist as $row){
		$userary[$row['id']]=$row['realname'];
	}
	for($i=0;$i<count($list);$i++){
		$list[$i]["username"]=$userary[$list[$i]['userid']];
	}
	die(json_encode(array('success'=>true,'list'=>$list,'pindex'=>$pindex,'total'=>$total)));
	
} elseif ($operation == 'exchangegift') {
	$fid=$_GPC['id'];
	$memberid=$_GPC['mid'];
	$member=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_membercard')." WHERE weid = '".$_W['uniacid']."' and id=:a ",array(":a"=>$memberid));
	$member['credit2']=$member['credit'];

    $uid=$member['uid'];
    if($uid){
        $this->memberCardInform($memberid);
        $memberuser=mc_fetch($uid);
        $member['credit2']=$memberuser['credit1'];
    }
	
	$gift = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_gift') . " WHERE weid = '".$_W['uniacid']."' and id=:a ",array(":a"=>$fid));
    if(intval($gift['credit']*100)>intval($member['credit2']*100))die(json_encode(array("success"=>false,"msg"=>"积分不足")));
	$datagift=array();
	if($gift['store']>0){
		if($gift['remain']==0)die(json_encode(array("success"=>false,"msg"=>"礼品数量不足")));
		$datagift['remain']=$gift['remain']-1;
	}
	pdo_update('j_hmoney_gift',$datagift,array('id'=>$fid));
	
	$outTradeno=TIMESTAMP;
	$data=array(
		"weid"=>$_W['uniacid'],
		"userid"=>$userid,
		"groupid"=>$shopid,
		"memberid"=>$memberid,
		"credit"=>$gift['credit'],
		"out_trade_no"=>$outTradeno,
		"giftid"=>$gift['id'],
		"title"=>$gift['title'],
		"gtype"=>$gift['gtype'],
		"status"=>"0",
		"createtime"=>TIMESTAMP,
	);
	pdo_insert("j_hmoney_giftrecord",$data);
	$tid=pdo_insertid();
	$datas=array();
	switch($gift['gtype']){
		case 0:
			$datas['status']=1;
		break;
		case 1:
			$content=$gift['content'];
			$favorAry=strpos($content,"|") ? explode("|",$content) : array($content);
			shuffle($favorAry);
			$cardkey=$favorAry[0];
			$datas['content']=$cardkey;
			$url=$this->IncreateQrcode($outTradeno,1);
			$datas['qrcode']=$url;
		break;
		case 2:
			$content=$gift['content'];
			if(strpos($content,"-")){
				$temp=explode("|",$content);
				$cash=mt_rand($temp[0]*100,$temp[1]*100);
			}else{
				$cash=$content*100;
			}
			$datas['content']=$cash;
			$url=$this->IncreateQrcode($outTradeno,1);
			$datas['qrcode']=$url;
		break;
		case 3:
			$content=$gift['content'];
			$datas['content']=$content;
			pdo_update("j_hmoney_membercard",array('cash'=>$member['cash']+$content*100),array('id'=>$memberid));
			$datas['status']=1;
			$datas['isget']=1;
			$datas['endtime']=TIMESTAMP;
			
		break;
	}
	pdo_update("j_hmoney_giftrecord",$datas,array('out_trade_no'=>$outTradeno));
    if(!$uid){
        pdo_update('j_hmoney_membercard',array('credit'=>$this->_2money(intval($member['credit']*100)-intval($gift['credit']*100))),array('id'=>$memberid));
    }else{
        mc_credit_update($uid,"credit1",(-1)*$gift['credit'],array("","收银系统-兑换礼品"));
    }
	$this->memberCardInform($memberid);
    die(json_encode(array("success"=>true,"out_trade_no"=>$outTradeno)));
	
} elseif ($operation == 'sendgift') {
    $id=$_GPC["id"];
    $giftrecord = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_giftrecord') . " WHERE weid = '".$_W['uniacid']."' and id=:a ",array(":a"=>$id));
    if($giftrecord['status']==1)die(json_encode(array("success"=>false,"msg"=>"奖品已经发送")));
    if($giftrecord['isget']==1)die(json_encode(array("success"=>false,"msg"=>"奖品已领取")));
    if($giftrecord['gtype']==0)die(json_encode(array("success"=>false,"msg"=>"实物无需补发")));
    if($giftrecord['gtype']==2){
        $result=$this->_sendpack($giftrecord['openid'],$giftrecord);
        if($result['errno']!=0)die(json_encode(array("success"=>false,"msg"=>$result['error'])));
    }else{
        die(json_encode(array("success"=>true,"out_trade_no"=>$giftrecord["out_trade_no"])));
    }
    die(json_encode(array("success"=>true)));
	
} elseif ($operation == 'handover') {
    #$condition="and groupid ='".$shopid."' and userid='".$userid."' and createtime>='".strtotime("2017-08-01")."' and createtime<='".TIMESTAMP."' ";
    $condition="and groupid ='".$shopid."' and userid='".$userid."' and createtime>='".$user['lasttime']."' and createtime<='".TIMESTAMP."'";
    $items = pdo_fetch('SELECT COUNT(*) as num1,sum(order_fee) as fee1,sum(discount_fee) as fee2,sum(total_fee) as fee3,sum(num) as num2 FROM '.tablename('j_hmoney_order')." WHERE weid='{$_W['uniacid']}' $condition  and ispay=1");
    $paytypeList1 = pdo_fetchall('SELECT paytype,COUNT(*) as num1,sum(paid_fee1) as fee1 FROM '.tablename('j_hmoney_order')." WHERE weid='{$_W['uniacid']}' $condition  and ispay=1 group by paytype ");
    $paytypeList2 = pdo_fetchall('SELECT paytype2,COUNT(*) as num1,sum(paid_fee2) as fee1 FROM '.tablename('j_hmoney_order')." WHERE weid='{$_W['uniacid']}' $condition  and ispay=1 and paytype2>-1 group by paytype2 ");
    $paytypeList=array();
    $temp=_getPaytpye("",$shopid);
    foreach($paytypeList1 as $row){
        $paytypeList[$row["paytype"]]=array(
            "num"=>$row["num1"],
            "fee1"=>$row["fee1"],
        );
    }
    foreach($paytypeList2 as $row){
        if(!isset($paytypeList[$row["paytype2"]]))$paytypeList[$row["paytype2"]]=array("num"=>0,"fee1"=>0);
        $paytypeList[$row["paytype2"]]["num"]=$paytypeList[$row["paytype2"]]["num"]+$row["num1"];
        $paytypeList[$row["paytype2"]]["fee1"]=$paytypeList[$row["paytype2"]]["fee1"]+$row["fee1"];
    }
    $holdorder= pdo_fetchcolumn('SELECT COUNT(*) FROM '.tablename('j_hmoney_order')." WHERE weid='{$_W['uniacid']}' and groupid ='".$shopid."'  and status=0");
    /*充值部分*/
    $chargeitems = pdo_fetch('SELECT COUNT(*) as num1,sum(cash) as fee1 FROM '.tablename('j_hmoney_recharge')." WHERE weid='{$_W['uniacid']}' $condition  and status=1 and usetype=0 ");
    $chargecount = pdo_fetchall("SELECT paytype,sum(cash) as fee1 FROM " . tablename('j_hmoney_recharge') . " WHERE weid='{$_W['uniacid']}' $condition and usetype=0 and  status=1 group by paytype");
    $chargelist=array();
    foreach($chargecount as $row){
        $chargelist[$row["paytype"]]=$row["fee1"];
    }
    $membercount = pdo_fetchcolumn("SELECT count(*) FROM " . tablename('j_hmoney_membercard') . " WHERE weid='{$_W['uniacid']}' and userid='".$userid."' and createtime>='".$user['lasttime']."' and createtime<='".TIMESTAMP."' ");

	die(json_encode(array("success"=>true,"item"=>$items,"paytypelist"=>$paytypeList,"holdorder"=>$holdorder,"chargeitems"=>$chargeitems,"chargelist"=>$chargelist,"member"=>$membercount,"time"=>date('Y/m/d H:i',$user['lasttime'])."-".date('m/d H:i'))));
	
} elseif ($operation == 'refundgood') {
	$gid=$_GPC["id"];
	$num=$_GPC["num"];
	$fee=$_GPC["fee"];
	$remark=$_GPC["remark"];
	$goods=pdo_fetch("SELECT * FROM " . tablename('j_hmoney_ordergoods') . " WHERE weid = '{$_W['uniacid']}' and id=:a ",array(":a"=>$gid));
	if($goods['ispay']!=1)die(json_encode(array("success"=>true,"msg"=>"商品异常不能退款")));
	if($goods['total_fee']==0)die(json_encode(array("success"=>true,"msg"=>"商品已退款")));
	$result=$this->fun_refunder(2,$gid,$userid,$shopid,$remark,$num,$fee);
	die(json_encode($result));
	
} elseif ($operation == 'refundorder') {
    $orderid=$_GPC["orderid"];
    $remark=$_GPC["remark"];
    $paytype=$_GPC["paytype"];
    $gid=$_GPC["id"];
    $num=$_GPC["num"];
    $isgetback=intval($_GPC["isgetback"]);
    $fee=intval($_GPC["fee"]*100);
    if(!$gid){
        $order=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_order')." WHERE weid = '".$_W['uniacid']."' and id=:a",array(":a"=>$orderid));
        if($order['ispay']!=1)die(json_encode(array("success"=>true,"msg"=>"订单异常不能退款")));
        if($order['paid_fee']==0)die(json_encode(array("success"=>true,"msg"=>"订单已退款")));
        if($order['paid_fee']<$fee)die(json_encode(array("success"=>true,"msg"=>"退款金额大于支付金额")));
        $result=$this->fun_refunder(1,$orderid,$userid,$shopid,$remark,0,$fee,$paytype,$isgetback);
    }else{
        $goods=pdo_fetch("SELECT * FROM " . tablename('j_hmoney_ordergoods') . " WHERE weid = '{$_W['uniacid']}' and id=:a ",array(":a"=>$gid));
        if($goods['ispay']!=1)die(json_encode(array("success"=>true,"msg"=>"商品异常不能退款")));
        if($goods['total_fee']==0)die(json_encode(array("success"=>true,"msg"=>"商品已退款")));
        $result=$this->fun_refunder(2,$gid,$userid,$shopid,$remark,$num,$fee,$paytype,$isgetback);
    }
    die(json_encode($result));
	
} elseif ($operation == 'paysuccess') {
	$orderid=$_GPC["orderid"];
	$order=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_order')." WHERE weid = '".$_W['uniacid']."' and id=:a",array(":a"=>$orderid));
	
	if(!$order || $order['isconfirm'] || !$order['ispay'])die(json_encode(array('success'=>false,'msg'=>"订单异常")));
	load()->func('communication');
	/*发送通知*/
	$temstr=urldecode($cfg['tempmsg_payparama']);
	$tempstr=str_replace("|单号|",$order['out_trade_no'],$temstr);
	$tempstr=str_replace("|店铺|",$shop['companyname'],$tempstr);
	$tempstr=str_replace("|时间|",date("m/d H:i",$order['createtime']),$tempstr);
	$tempstr=str_replace("|处理人|",$user['realname'],$tempstr);
	$tempstr=str_replace("|总金额|","￥".$this->_2money(($order['order_fee'])),$tempstr);
	$tempstr=str_replace("|茶位|","￥".$this->_2money(($order['teafee'])),$tempstr);
	$tempstr=str_replace("|优惠|","￥".$this->_2money(($order['discount_fee'])),$tempstr);
	$tempstr=str_replace("|实付金额|","￥".$this->_2money(($order['paid_fee'])),$tempstr);
    $paystr=_getPaytpye($order['paytype'],$shopid);
    if($order['paid_fee2'])$paystr.=_getPaytpye($order['paytype'],$shopid);
	$tempstr=str_replace("|支付方式|",$paystr,$tempstr);
	$tempstr=str_replace("|数量|",$order['num'],$tempstr);
	$itemary=json_decode($tempstr,true);
	$temp=array();
	foreach($itemary as $key=>$val){
		$temp[$key]=array(
			"value"=>$val['value'],
			"color"=>$val['color'] ? $val['color']: "#333333",
		);
	}
	$temp['remark']["value"]="详细收款情况请登录后台查看";
	$acid=pdo_fetchcolumn("SELECT acid FROM ".tablename('account')." WHERE uniacid=:uniacid ",array(':uniacid'=>$_W['uniacid']));
	$acc = WeAccount::create($acid);
	if($user['openid'])$acc->sendTplNotice($user['openid'],$cfg["tempmsg_pay"],$temp,"","#FF0000");
	$userlist=pdo_fetchall("SELECT openid FROM ".tablename('j_money_user')." WHERE  pcate=:a and permission=3 ",array(":a"=>$order['groupid']));
	if(count($userlist)){
		foreach($userlist as $row){
			if($row["openid"]==$user['openid'])continue;
			$data=$acc->sendTplNotice($row["openid"],$cfg["tempmsg_pay"],$temp,"","#FF0000");
		}
	}
	if($order['openid']){
		$temp['remark']["value"]="谢谢惠顾";
		$data=$acc->sendTplNotice($order['openid'],$cfg["tempmsg_pay"],$temp,"","#FF0000");
	}
    if($order['memberno']){
        $memberopenid = pdo_fetchcolumn("SELECT openid FROM " . tablename('j_hmoney_membercard') . " WHERE weid = '{$_W['uniacid']}' and id=:a", array(":a" => $order['memberno']));
        $temp['remark']["value"]="谢谢惠顾";
        if($order['memberno'])$data=$acc->sendTplNotice($order['openid'],$cfg["tempmsg_pay"],$temp,"","#FF0000");
    }
	pdo_update("j_hmoney_order",array("isconfirm"=>1),array("id"=>$orderid));
	/*发送通知完成*/
	/*检查是否有优惠活动*/
	$qrcode=$this->IncreateQrcode($order['out_trade_no'],2,1);
	pdo_update("j_hmoney_order",array("qrcode"=>$qrcode),array("id"=>$orderid));
	die(json_encode(array('success'=>true)));
	
} elseif ($operation == 'getmessage') {
	$list=pdo_fetchall("SELECT * FROM ".tablename('j_hmoney_msg')." WHERE  groupid=:a  and createtime>=:b order by id desc",array(":a"=>$shopid,":b"=>strtotime(date("Y-m-d")." 00:00:00")));
	for($i=0;$i<count($list);$i++){
		$list[$i]['time']=date("m月d日 H:i",$list[$i]['createtime']);
	}
	die(json_encode(array('success'=>true,'list'=>$list)));

} elseif ($operation == 'gettoday') {
    $condition=" and groupid ='".$shopid."' and createdate='".date("Y-m-d")."' ";
    $items = pdo_fetch('SELECT COUNT(*) as num1,sum(order_fee) as fee1,sum(discount_fee) as fee2,sum(total_fee) as fee3,sum(num) as num2 FROM '.tablename('j_hmoney_order')." WHERE weid='{$_W['uniacid']}' $condition  and ispay=1");
    $paytypeList1 = pdo_fetchall('SELECT paytype,COUNT(*) as num1,sum(paid_fee1) as fee1 FROM '.tablename('j_hmoney_order')." WHERE weid='{$_W['uniacid']}' $condition  and ispay=1 group by paytype ");
    $paytypeList2 = pdo_fetchall('SELECT paytype2,COUNT(*) as num1,sum(paid_fee2) as fee1 FROM '.tablename('j_hmoney_order')." WHERE weid='{$_W['uniacid']}' $condition  and ispay=1 and paytype2>-1 group by paytype2 ");
    $paytypeList=array();
    $temp=_getPaytpye("",$shopid);
    foreach($paytypeList1 as $row){
        $paytypeList[$row["paytype"]]=array(
            "num"=>$row["num1"],
            "fee1"=>$row["fee1"],
        );
    }
    foreach($paytypeList2 as $row){
        if(!isset($paytypeList[$row["paytype2"]]))$paytypeList[$row["paytype2"]]=array("num"=>0,"fee1"=>0);
        $paytypeList[$row["paytype2"]]["num"]=$paytypeList[$row["paytype2"]]["num"]+$row["num1"];
        $paytypeList[$row["paytype2"]]["fee1"]=$paytypeList[$row["paytype2"]]["fee1"]+$row["fee1"];
    }
    $holdorder= pdo_fetchcolumn('SELECT COUNT(*) FROM '.tablename('j_hmoney_order')." WHERE groupid ='".$shopid."'  and status=0 ");
    /*充值部分*/
    $chargeitems = pdo_fetch('SELECT COUNT(*) as num1,sum(cash) as fee1 FROM '.tablename('j_hmoney_recharge')." WHERE weid='{$_W['uniacid']}' $condition  and status=1 and usetype=0 ");
    $chargecount = pdo_fetchall("SELECT paytype,sum(cash) as fee1 FROM " . tablename('j_hmoney_recharge') . " WHERE weid='{$_W['uniacid']}' $condition and usetype=0 and  status=1 group by paytype");
    $chargelist=array();
    foreach($chargecount as $row){
        $chargelist[$row["paytype"]]=$row["fee1"];
    }
    $membercount = pdo_fetchcolumn("SELECT count(*) FROM " . tablename('j_hmoney_membercard') . " WHERE groupid ='".$shopid."' and createtime>='".strtotime(date("Y-m-d 00:00:00"))."' ");
    /*退款汇总*/
    $refunditems = pdo_fetchall('SELECT COUNT(*) as num1,sum(fee) as fee1,paytype FROM '.tablename('j_hmoney_refund')." WHERE weid='{$_W['uniacid']}' $condition  and status=1 group by paytype order by id desc ");
    $refundlist=array();
    $refundall=0;
    foreach($refunditems as $row){
        $refundlist[$row["paytype"]]=$row["fee1"];
        $refundall+=$row["fee1"];
    }
    $refundlist["all"]=$refundall;
    die(json_encode(array("success"=>true,"item"=>$items,"paytypelist"=>$paytypeList,"holdorder"=>$holdorder,"chargeitems"=>$chargeitems,"chargelist"=>$chargelist,"member"=>$membercount,"refundlist"=>$refundlist,"time"=>date('Y/m/d H:i',$user['lasttime'])."-".date('m/d H:i'))));

} elseif ($operation == 'gettodaygoods') {
    $condition=" and a.groupid ='".$shopid."' and a.createtime>='".strtotime(date("Y-m-d 00:00:00"))."' and a.createtime<='".strtotime(date("Y-m-d 23:59:59"))."'";
    $items = pdo_fetchall('SELECT max(a.title) as title2, max(a.goodsn) as sn,sum(a.num) as num1,sum(a.total_fee) as fee1,b.marketprice,AVG(a.price) as price2 FROM '.tablename('j_hmoney_ordergoods')." a left join ".tablename('j_hmoney_goods')." b on a.goodid=b.id WHERE a.weid='{$_W['uniacid']}' $condition  and a.ispay=1 group by a.goodid order by sum(a.num) desc");
    die(json_encode(array("success"=>true,"list"=>$items)));
}
if($_GPC["screen"]){
    include $this->template($cfg['floder'].'/index1024');
}else{
    include $this->template($cfg['floder'].'/index');
}












